<script setup lang="ts">
import {
  Modal,
  Form,
  FormItem,
  FormInstance,
  Select,
  message,
  SelectProps,
} from "ant-design-vue";

import { Service } from "../api";
import { reactive, ref, watch } from "vue";
const open = defineModel<boolean>("open", { required: true });
const props = defineProps<{
  musicId: number;
}>();
const emits = defineEmits<{
  finish: [];
  toReigister: [];
}>();
const formRef = ref<FormInstance>();
const formState = reactive<{
  playlistId?: number;
}>({});

const options = ref<SelectProps["options"]>();
const loadOptions = async () => {
  const playlists = await Service.getAllPlaylist();
  options.value = playlists.map((playlist) => {
    return {
      value: playlist.id,
      label: playlist.title,
    };
  });
};

const loading = ref(false);
const submit = async () => {
  try {
    await formRef.value?.validate();
    await Service.addMusicInfoToPlaylist({
      musicId: props.musicId,
      playlistId: formState.playlistId as number,
    });
    emits("finish");
    open.value = false;
    message.success("添加成功");
  } catch (error) {}
};
watch(open, () => {
  if (open) {
    formRef.value?.resetFields();
  }
});
watch(
  () => props.musicId,
  () => {
    loadOptions();
  },
  {
    immediate: true,
  }
);
</script>
<template>
  <Modal
    v-model:open="open"
    title="添加到歌单"
    @ok="submit"
    ok-text="确定"
    cancel-text="取消"
    :confirmLoading="loading"
  >
    <Form
      ref="formRef"
      :model="formState"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
    >
      <FormItem
        label="歌单"
        name="playlistId"
        :rules="[{ required: true, message: '歌单不能为空' }]"
      >
        <Select
          v-model:value="formState.playlistId"
          :options="options"
          placeholder="选择歌单"
        >
        </Select>
      </FormItem>
    </Form>
  </Modal>
</template>
